import React from 'react';
import {
  View,
  Image,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import Badge from './common/Badge';
import { COLORS, RADIUS, FONT_WEIGHT, SPACING } from '../styles/constants';

/**
 * MasonryCarousel 瀑布式横向轮播：
 * - 第一个卡片为大图（占一列）
 * - 其余全部为上下堆叠的小图列（每列两张）
 */

export default function MasonryCarousel({ items = [], onPress }) {
  // 生成列：第一列大图，后续每列两张小图
  const columns = [];
  if (items.length > 0) {
    columns.push({ type: 'big', item: items[0] });
  }
  for (let i = 1; i < items.length; i += 2) {
    columns.push({
      type: 'stack',
      items: [items[i], items[i + 1]].filter(Boolean),
    });
  }

  const renderColumn = ({ item }) => {
    if (item.type === 'big') {
      const g0 = item.item;
      const distance = g0.raw?.distance || g0.distance;
      const level = g0.raw?.level || g0.level;
      return (
        <View style={styles.group}>
          <TouchableOpacity style={styles.big} onPress={() => onPress?.(g0)}>
            <Image
              source={{ uri: g0.image }}
              style={styles.bigImg}
              resizeMode="cover"
            />
            {level && (
              <Badge
                text={level}
                type="level"
                size="md"
                style={styles.topLeftBadge}
              />
            )}
            {distance && (
              <Badge
                text={distance}
                type="distance"
                size="md"
                style={styles.topRightBadge}
              />
            )}
            {g0.title && (
              <Text style={styles.title} numberOfLines={1}>
                {g0.title}
              </Text>
            )}
          </TouchableOpacity>
        </View>
      );
    }
    const [g1, g2] = item.items;
    return (
      <View style={styles.group}>
        <View style={styles.rightCol}>
          {g1 && (
            <TouchableOpacity
              style={styles.smallCard}
              onPress={() => onPress?.(g1)}
            >
              <Image
                source={{ uri: g1.image }}
                style={styles.smallImg}
                resizeMode="cover"
              />
              {(g1.raw?.level || g1.level) && (
                <Badge
                  text={g1.raw?.level || g1.level}
                  type="level"
                  size="sm"
                  style={styles.topLeftBadgeSmall}
                />
              )}
              {(g1.raw?.distance || g1.distance) && (
                <Badge
                  text={g1.raw?.distance || g1.distance}
                  type="distance"
                  size="sm"
                  style={styles.topRightBadgeSmall}
                />
              )}
              {g1.title && (
                <Text style={styles.smallTitle} numberOfLines={2}>
                  {g1.title}
                </Text>
              )}
            </TouchableOpacity>
          )}
          {g2 && (
            <TouchableOpacity
              style={styles.smallCard}
              onPress={() => onPress?.(g2)}
            >
              <Image
                source={{ uri: g2.image }}
                style={styles.smallImg}
                resizeMode="cover"
              />
              {(g2.raw?.level || g2.level) && (
                <Badge
                  text={g2.raw?.level || g2.level}
                  type="level"
                  size="sm"
                  style={styles.topLeftBadgeSmall}
                />
              )}
              {(g2.raw?.distance || g2.distance) && (
                <Badge
                  text={g2.raw?.distance || g2.distance}
                  type="distance"
                  size="sm"
                  style={styles.topRightBadgeSmall}
                />
              )}
              {g2.title && (
                <Text style={styles.smallTitle} numberOfLines={2}>
                  {g2.title}
                </Text>
              )}
            </TouchableOpacity>
          )}
        </View>
      </View>
    );
  };

  return (
    <FlatList
      horizontal
      showsHorizontalScrollIndicator={false}
      data={columns}
      keyExtractor={(_, idx) => String(idx)}
      renderItem={renderColumn}
      contentContainerStyle={styles.list}
    />
  );
}

const CARD_H = 200;

const styles = StyleSheet.create({
  list: { paddingHorizontal: SPACING.lg },
  group: { flexDirection: 'row', marginRight: SPACING.md },
  big: {
    width: 260,
    height: CARD_H,
    borderRadius: RADIUS.md,
    overflow: 'hidden',
    marginRight: SPACING.md,
    backgroundColor: COLORS.background.secondary,
    borderWidth: 1,
    borderColor: COLORS.border.medium,
  },
  bigImg: { width: '100%', height: '100%' },
  topLeftBadge: {
    position: 'absolute',
    top: SPACING.sm,
    left: SPACING.sm,
  },
  topRightBadge: {
    position: 'absolute',
    top: SPACING.sm,
    right: SPACING.sm,
  },
  topLeftBadgeSmall: {
    position: 'absolute',
    top: 6,
    left: 6,
  },
  topRightBadgeSmall: {
    position: 'absolute',
    top: 6,
    right: 6,
  },
  rightCol: { width: 190, justifyContent: 'space-between' },
  smallCard: {
    height: (CARD_H - 8) / 2,
    borderRadius: RADIUS.md,
    marginBottom: SPACING.sm,
    overflow: 'hidden',
    position: 'relative',
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    backgroundColor: COLORS.background.secondary,
    borderWidth: 1,
    borderColor: COLORS.border.medium,
  },
  smallImg: {
    width: '100%',
    height: '100%',
  },
  title: {
    position: 'absolute',
    left: SPACING.sm,
    bottom: SPACING.sm,
    color: COLORS.white,
    fontWeight: FONT_WEIGHT.bold,
    textShadowColor: COLORS.background.overlay,
    textShadowRadius: 6,
    textShadowOffset: { width: 0, height: 2 },
  },
  smallTitle: {
    position: 'absolute',
    left: SPACING.sm,
    bottom: SPACING.sm,
    right: SPACING.sm,
    color: COLORS.white,
    fontWeight: FONT_WEIGHT.semibold,
    fontSize: 12,
    lineHeight: 16,
    textShadowColor: COLORS.background.overlay,
    textShadowRadius: 4,
    textShadowOffset: { width: 0, height: 1 },
  },
});
